using IM.Easy.Infrastructure.Query;
using Microsoft.AspNetCore.Mvc;
using IM.Easy.MsgServices.IServices;
using IM.Easy.Entity.Msg;
using IM.Easy.MsgServices.Dtos;
using Mapster;
using IM.Easy.Core.Attributes;
using IM.Easy.Api.Hubs;
using Microsoft.AspNetCore.SignalR;
using IM.Easy.Core.Utils;
using Microsoft.AspNetCore.Identity;
using IM.Easy.Api.AccountManage;
using IM.Easy.Core.AppContext;

namespace IM.Easy.Api.Controllers.Msg
{
    /// <summary>
    /// EmailsController 控制器
    /// </summary>
    [Route("msg/emails")]
    public class EmailsController : ControllerBase
    {
        private readonly IEmailsService _service;
        private readonly IEmailRecivesService _serviceRecives;
        private readonly IEmailAccountService _accountService;
        private readonly IHubContext<UserHub> _hubContext;
        private readonly IOnlineService _onlineUserManager;

        /// <summary>
        /// 构造函数，注入服务
        /// </summary>
        /// <param name="service">服务接口</param>
        public EmailsController(IEmailsService service, IEmailRecivesService serviceRecives, IEmailAccountService emailAccountService, IHubContext<UserHub> hubContext, IOnlineService onlineService)
        {
            _service = service;
            _serviceRecives = serviceRecives;
            _accountService = emailAccountService;
            _hubContext = hubContext;
            _onlineUserManager = onlineService;
        }

        /// <summary>
        /// 获取所有Emails对象
        /// </summary>
        /// <returns>返回Emails列表</returns>
        [HttpGet]
        [Api(Name = "获取草稿箱", Perm = "msg:email:list")]
        public PageResponse<EmailsDto> GetList([FromQuery] EmailsQueryDto query)
        {
            query.SenderId = ImApp.User.Id;
            return _service.GetPageList(query);
        }

        /// <summary>
        /// 根据ID获取Emails对象
        /// </summary>
        /// <param name="id">对象的ID</param>
        /// <returns>返回指定的Emails对象</returns>
        [HttpGet("{id}")]
        [Api(Name = "获取草稿箱", Perm = "msg:email:info")]
        public EmailsDto GetById([FromRoute] int id)
        {
            var result = _service.GetById(id);
            var response = result.Adapt<EmailsDto>();
            return response ?? throw new KeyNotFoundException($"未找到ID为 {id} 的Emails对象。");
        }

        /// <summary>
        /// 创建新的Emails对象
        /// </summary>
        /// <param name="entity">要创建的Emails对象</param>
        /// <returns>返回创建后的Emails对象</returns>
        [HttpPost]
        [Api(Name = "保存邮件", Perm = "msg:email:save")]
        public Emails Save([FromBody] EmailsCreateDto entity)
        {
            var email = _service.Save(entity);
            return email;
        }

        /// <summary>
        /// 批量删除Emails对象
        /// </summary>
        /// <param name="ids">对象的IDS</param>
        [HttpDelete]
        [Api(Name = "删除邮件", Perm = "msg:email:del")]
        public void Delete([FromBody] int[] ids)
        {
            _service.Delete(ids);
        }

        /// <summary>
        /// 发送邮件
        /// </summary>
        [HttpPut("send")]
        [Api(Name = "发送邮件", Perm = "msg:email:send")]
        public async Task<bool> Send([FromBody] EmailsCreateDto createDto)
        {
            var email = _service.Save(createDto);
            _service.Send(email.Id);
            var result = _serviceRecives.Recive(email.Id, [.. createDto.AudienceId]);

            #region 通知在线用户
            var users = _accountService.GetUser([.. createDto.AudienceId]);
            var uids = users.Select(s => s.Id);

            var connid = _onlineUserManager.UserConnections.Where(s => users.Any(u => u.Id.ToString() == s.UserId)).Select(s => s.ConnectionId).ToList();

            await _hubContext.Clients.Clients(connid).SendAsync("ReceiveEmail", createDto.Subject, createDto.Abstract, ImApp.User.UserName);
            #endregion
            return result;
        }

    }
}
